<template>
    <div>
        <Modal v-model="modal.add" title="添加" :mask-closable="false" @on-visible-change="changeModalVisibleResetForm('addForm', $event)" width="1020">
            <Form ref="addForm" :model="form" :label-width="120" :rules="validateRules">
                <Row>
	<i-col span="12">
	<FormItem label="配置名称" prop="name">
	<Input v-model="form.name" placeholder="请输入配置名称" clearable/>
</FormItem>
	</i-col><i-col span="12">
	<FormItem label="配置内容(JSON)" prop="value">
        <vue-json-editor style="height: 250px;" v-model="form.value" :showBtns="false"></vue-json-editor>
</FormItem>
	</i-col>

	<i-col span="12">
	<FormItem label="中文说明" prop="description">
	<Input v-model="form.description" placeholder="请输入中文说明" clearable/>
</FormItem>
	</i-col><i-col span="12">
	<FormItem label="配置注释" prop="comment">
        <vue-json-editor v-model="form.comment" :showBtns="false"></vue-json-editor>
</FormItem>
	</i-col>

	<i-col span="12">
		<FormItem label="允许外部访问" prop="outsideAccess">
		    
		        <Select v-model="form.outsideAccess" placeholder="允许外部访问" filterable clearable>
		          <Option
		            v-for="(option, index) in outsideAccessSelect"
		            :value="option.value"
		            :key="index"
		          >{{option.displayValue}}</Option>
		        </Select>
		    
		</FormItem>
	
	</i-col>
</Row>

            </Form>
            <div slot="footer">
                <Button type="text" size="large" @click="resetFormCancelModal('addForm', 'add')">取消</Button>
                <Button type="primary" size="large" @click="add" :loading="loading.add">添加</Button>
            </div>
        </Modal>
        <Modal v-model="modal.edit" title="修改" :mask-closable="false" @on-visible-change="changeModalVisibleResetForm('editForm', $event)" width="1020">
            <Form ref="editForm" :model="form" :label-width="120" :rules="validateRules">
                <Row>
	<i-col span="12">
	<FormItem label="配置名称" prop="name">
	<Input v-model="form.name" placeholder="请输入配置名称" clearable/>
</FormItem>
	</i-col><i-col span="12">
	<FormItem label="配置内容(JSON)" prop="value">
        <vue-json-editor ref="jsonEditor" v-model="form.value" :showBtns="false"></vue-json-editor>
</FormItem>
	</i-col>

	<i-col span="12">
	<FormItem label="中文说明" prop="description">
	<Input v-model="form.description" placeholder="请输入中文说明" clearable/>
</FormItem>
	</i-col><i-col span="12">
	<FormItem label="配置注释" prop="comment">
        <vue-json-editor v-model="form.comment" :showBtns="false"></vue-json-editor>
</FormItem>
	</i-col>

	<i-col span="12">
	<FormItem label="允许外部访问" prop="outsideAccess">
	    
	        <Select v-model="form.outsideAccess" placeholder="允许外部访问" filterable clearable>
	          <Option
	            v-for="(option, index) in outsideAccessSelect"
	            :value="option.value"
	            :key="index"
	          >{{option.displayValue}}</Option>
	        </Select>
	    
	</FormItem>
	</i-col>
</Row>
        <Row v-if="form.name == 'sys_pic_config'">
          <i-col span="12" v-for="(item, index) in itemList" :key="index">
            <FormItem :label="item.label" :prop="item.key">
              <div class="demo-upload-list" v-if="item.value">
                <img :src="item.value" />
                <div class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline" @click.native="handleView(item.value)"></Icon>
                  <Icon type="ios-trash-outline" @click.native="handleRemove(item.key, index)"></Icon>
                </div>
              </div>
              <Upload
                ref="uploadIcon"
                :show-upload-list="false"
                :on-success="handleSuccess"
                :format="['jpg','jpeg','png']"
                :max-size="2048"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                :on-progress="handleProgress"
                type="drag"
                :data="{type: item.key}"
                :action="urls.uploadUrl"
                :headers="uploadHeader"
                style="display: inline-block;width:58px;"
              >
                <div style="width: 58px;height:58px;line-height: 58px;">
                  <Icon type="ios-camera" size="20"></Icon>
                </div>
              </Upload>
            </FormItem>
          </i-col>
        </Row>

            </Form>
            <div slot="footer">
                <Button type="text" size="large" @click="resetFormCancelModal('editForm', 'edit')">取消</Button>
                <Button type="primary" size="large" @click="edit" :loading="loading.edit">修改</Button>
            </div>
        </Modal>
        <Modal title="预览图片" v-model="visible">
          <img :src="imgUrl" v-if="visible" style="width: 100%" />
        </Modal>
    </div>
</template>

<script>
	import * as utils from '@/api/utils-v2'
    import vueJsonEditor from 'vue-json-editor'
    import * as ResponseStatus from '@/api/response-status'
import config from '@/config'
const baseUrl =
  process.env.NODE_ENV === 'development'
    ? config.baseUrl.dev
    : config.baseUrl.pro
const cdnUrl = config.baseUrl.cdnUrl

import { getLocalStorageToken, localStorage } from '@/libs/util'
    export default {
        name: 'SysConfigAddEdit',
        components: {
            vueJsonEditor
        },
        data() {
            return {
                modal: {
                    add: false,
                    edit: false
                },
                loading: {
                    add: false,
                    edit: false
                },
				dataDictCodes: ['SYS_CONFIG_OUTSIDE_ACCESS'],
				dataDictItems: {},
				outsideAccessSelect:[],
                urls: {
                    addUrl: '/sys-config/admin/save',
                    batchAddUrl: '/sys-config/admin/batch-save',
                    editUrl: '/sys-config/admin/update',
                    batchEditUrl: '/sys-config/admin/batch-update',
                    uploadUrl: baseUrl + '/sys-config/admin/upload-img'
                },
                form: {
                    name: null,
value: null,
description: null,
comment: null,
outsideAccess: null,

                },
                validateRules: {
                    name: [
{type: 'string', required: true, message: '此项为必须项', trigger: 'blur'},
{type: 'string', min: 1, max: 50, message: '必须1-50个字符', trigger: 'blur'}
],
value: [
{type: 'string', required: true, message: '此项为必须项', trigger: 'blur'},
{type: 'string', min: 1, max: 5000, message: '必须1-5000个字符', trigger: 'blur'}
],
description: [
{type: 'string', min: 1, max: 50, message: '必须1-50个字符', trigger: 'blur'}
],
comment: [
{type: 'string', min: 1, max: 5000, message: '必须1-5000个字符', trigger: 'blur'}
],

                },
                itemList: [],
                uploadHeader: {
                  Authorization: 'Bearer ' + getLocalStorageToken()
                },
                imgUrl: '',
                visible: false
            }
        },
        computed: {},
        mounted() {
			            utils.getDataDict(this.dataDictCodes).then(response => {
			              if (response) {
			                this.dataDictItems = response
			                utils.getSelectDictItems(this, 'SYS_CONFIG_OUTSIDE_ACCESS', 'outsideAccess', 'outsideAccessSelect')
			              }
			            }).catch(error => {
			              console.log(error)
			            })
		},
        methods: {
            changeModalVisibleResetForm(formRef, visible) {
                if (!visible) {
					this.$refs[formRef].resetFields()
					this.form.id = null
                }
            },
            resetFormCancelModal(formRef, modal) {
                this.modal[modal] = false
				this.$refs[formRef].resetFields()
				this.form.id = null
            },
            add() {
                this.form.value = JSON.stringify(this.form.value)
                this.form.comment = JSON.stringify(this.form.comment)
                this.$emit('add')
            },
            edit() {
                this.form.value = JSON.stringify(this.form.value)
                this.form.comment = JSON.stringify(this.form.comment)
                this.$emit('edit')
            },
            /**
             * 查看图片
             */
            handleView(url) {
              this.imgUrl = url
              this.visible = true
            },
            /**
             * 移除图片
             */
            handleRemove(itemName, index) {
              this.itemList[index].value = ''
              this.form.value[itemName] = ''
            },
            /**
             * 上传成功
             */
            handleSuccess(res, file) {
              if (res.code === ResponseStatus.OK) {
                this.$Notice.success({
                  title: '上传成功',
                  desc: file.name + ' 上传成功'
                })
                const url = cdnUrl + '/' + res.data
                const type = res.message
                this.form.value[type] = url
                this.$refs.jsonEditor.editor.set(this.form.value)
                this.itemList.forEach(item => {
                  if (item.key === type) {
                    item.value = url
                  }
                })
              } else {
                this.$Notice.error({
                  title: '上传失败',
                  desc: res.message
                })
              }
            },
            /**
             * 格式化异常
             */
            handleFormatError(file) {
              this.$Notice.warning({
                title: '文件格式不正确',
                desc: file.name + ' 的文件格式不正确，请选择JPG或PNG。'
              })
            },
            /**
             * 图片大小异常
             */
            handleMaxSize(file) {
              this.$Notice.warning({
                title: '超出文件大小限制',
                desc: file.name + ' 太大，不超过2M.'
              })
            },
            /**
             * 图片开始上传
             */
            handleProgress(event, file) {
              this.$Notice.info({
                title: '文件正在上传',
                desc: file.name + ' 上传中...'
              })
            }
        }
    }
</script>

<style>
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
/** vue-json-editor的高度 */
div.jsoneditor {
  height: 250px;
}
</style>
